﻿using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using jTCodeGenerate.Models;
using System.IO;
using Newtonsoft.Json;
using jTCodeGenerate.UserForms;
using jTCodeGenerate.Command;
using System.Data;
using static jTCodeGenerate.Command.ClassHelper;
using JinianNet.JNTemplate;

namespace jTCodeGenerate
{
    public partial class MainForm : Form
    {
        private DTE2 _dte;
        private static IList<ClassModel> _ClassModels;
        // 解决方案中的所有项目        

        private IList<Project> _SolutionProjects;
        private MainCommandBase command;
        private string _ignoreNamespace = Command.SQLCommand.GetSettingValue("IgnoreNamespace");
        public MainForm(DTE2 dte)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            InitializeComponent();
            Init(dte);
        }
        private void Init(DTE2 dte)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                _dte = dte;
                command = MainCommandBase.Instance;
                _SolutionProjects = command.GetSolutionProjects(_dte.Solution);
                command.Init(dte, _SolutionProjects);
                InitModelData();
                InitTree();
                InitGridView();
                InitTemplateGridView();
                LoadTemplateGird();

                var data = SQLCommand.GetSolutionAll();
                this.cmb_sol.DataSource = data;
                this.cmb_sol.DisplayMember = "Name";
                this.cmb_sol.ValueMember = "Id";
                this.cmb_sol.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"{ex}");
                throw ex;
            }
        }
        private void InitModelData()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var curClass = command.GetCurrentClass(_dte);
            _ClassModels = new List<ClassModel>();
            foreach (var item in curClass)
            {
                var classProperties = command.GetClassProperty(item);
                var baseCodeClassLst = new List<CodeClass>();
                command.GetClassList(item.Bases, ref baseCodeClassLst);
                foreach (var co in baseCodeClassLst)
                {
                    if (co.Name == "Object")
                        continue;
                    var ca = command.GetClassProperty(co);
                    classProperties.AddRange(ca);
                }
                var talbeName = command.GetTableName(item.Attributes);
                if (string.IsNullOrWhiteSpace(talbeName))
                    talbeName = item.Name;
                _ClassModels.Add(new ClassModel
                {
                    ClassName = item.Name,
                    FullName = item.FullName,
                    TableName = talbeName,
                    ClassProperties = classProperties,
                    Namespace = item.Namespace.FullName,
                    Describe = command.GetDescription(item.Attributes)
                });
            }
        }

        private void InitTree()
        {
            treeView1.Nodes.Clear();
            TreeNode root = new TreeNode();
            root.Name = "全部";
            root.Text = "全部";
            //将数据集加载到树形控件当中
            foreach (var d in _ClassModels)
            {
                TreeNode node = new TreeNode();
                node.Name = d.FullName;
                node.Text = d.ClassName;
                root.Nodes.Add(node);
            }
            treeView1.Nodes.Add(root);
            treeView1.ExpandAll();
            //treeView1.CheckBoxes = true;
        }

        private void InitGridView()
        {
            this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridView1.BackgroundColor = System.Drawing.Color.White;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(new DataGridViewColumn { Name = "Column0", HeaderText = "选择", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView1.Columns.Add(new DataGridViewColumn { Name = "Column1", HeaderText = "字段名称", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView1.Columns.Add(new DataGridViewColumn { Name = "Column2", HeaderText = "字段类型", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView1.Columns.Add(new DataGridViewColumn { Name = "Column3", HeaderText = "字段描述", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView1.Columns.Add(new DataGridViewColumn { Name = "Column4", HeaderText = "字段注释", CellTemplate = new DataGridViewTextBoxCell() });
        }

        private void LoadGird(string fullName)
        {
            var en = _ClassModels.Where(c => c.FullName == fullName).FirstOrDefault();
            if (en != null)
            {
                dataGridView1.Rows.Clear();
                foreach (var item in en.ClassProperties)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    row.Cells.Add(new DataGridViewCheckBoxCell { Tag = item.PropertyName, Value = true });
                    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.PropertyName, ValueType = typeof(string) });
                    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.PropertyType, ValueType = typeof(string) });
                    row.Cells.Add(new DataGridViewTextBoxCell { Value = item.Describe, ValueType = typeof(string) });
                    row.Cells.Add(new DataGridViewTextBoxCell { Value = "", ValueType = typeof(string) });
                    dataGridView1.Rows.Add(row);
                }
            }
        }

        private void InitTemplateGridView()
        {
            this.dataGridView2.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridView2.BackgroundColor = System.Drawing.Color.White;
            this.dataGridView2.Columns.Clear();
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column0", HeaderText = "选择", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column1", HeaderText = "方案名称", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column2", HeaderText = "模板名称", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column3", HeaderText = "生成路径", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column4", HeaderText = "生成顺序", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column5", HeaderText = "实体后缀", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column6", HeaderText = "实体前缀", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column7", HeaderText = "忽略实体后缀", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column8", HeaderText = "忽略实体前缀", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column9", HeaderText = "表名后缀", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column10", HeaderText = "表名前缀", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column11", HeaderText = "忽略表名后缀", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column12", HeaderText = "忽略表名前缀", CellTemplate = new DataGridViewTextBoxCell() });
            this.dataGridView2.Columns.Add(new DataGridViewColumn { Name = "Column13", HeaderText = "忽略字段", CellTemplate = new DataGridViewTextBoxCell() });
        }

        private void LoadTemplateGird()
        {
            var templates = SQLCommand.GetTemplateAll();
            dataGridView2.Rows.Clear();
            foreach (var temp in templates)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewCheckBoxCell { Tag = temp, Value = false });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.SolName, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.DisplayName, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.EntityGeneratePath, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.Order, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.EntitySuffix, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.EntityPrefix, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.IgnoreEntitySuffix, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.IgnoreEntityPrefix, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.TableNameSuffix, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.TableNamePrefix, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.IgnoreTableNameSuffix, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.TableNamePrefix, ValueType = typeof(string) });
                row.Cells.Add(new DataGridViewTextBoxCell { Value = temp.IgnoreField, ValueType = typeof(string) });

                dataGridView2.Rows.Add(row);
            }
        }

        private List<DataGridViewRow> GetSelectGridRow(DataGridView dataGridView)
        {
            var selectRow = new List<DataGridViewRow>();
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                var val = row.Cells[0].Value;
                bool.TryParse(val?.ToString(), out bool result);
                if (result)
                    selectRow.Add(row);
            }
            return selectRow;
        }

        /// <summary>
        /// 处理父节点，子节点的选中
        /// </summary>
        /// <param name="node">需要选中的树</param>
        /// <param name="state">选中/不选中</param>
        public static void SetTreeNodeCheckBoxState(TreeNode node, bool state)
        {
            if (node == null)
                return;
            node.Checked = state;
            foreach (TreeNode node2 in node.Nodes)
                node2.Checked = state;
            // 如果子级全部选中
            if (node.Parent != null)
            {
                node.Parent.Checked = false;
                if (!node.Parent.Nodes.Cast<TreeNode>().Where(c => c.Checked == false).Any())
                {
                    node.Parent.Checked = true;
                }
            }
        }

        private TableModel GenerateCreateTableSql(ClassModel model)
        {
            var tableModel = new TableModel();
            foreach (var field in model.ClassProperties)
            {
                var isKey = false;
                var isInc = false;
                // 如果是数字类型则自增
                if (field.ColumnName.ToLower().Contains("id"))
                {
                    isKey = true;
                    if (field.PropertyType.ToLower() == "int" || field.PropertyType.ToLower() == "long")
                        isInc = true;
                }
                var en = new TableFieldModel
                {
                    Describe = field.Describe,
                    Field = field.ColumnName,
                    FieldLength = field.MaxLength,
                    IsKey = isKey,
                    DefaultValue = "0",
                    IsInc = isInc
                };
                command.MySqlSetField(field.PropertyType, field.MaxLength, ref en);
                tableModel.TableName = model.TableName;
                tableModel.Describe = model.Describe;
                tableModel.TableFieldModels.Add(en);
            }
            return tableModel;
        }

        private void GetGenerateField(ClassModel mode)
        {
            if (mode == null)
                return;
            var rows = GetSelectGridRow(this.dataGridView1);
            var fieldName = new List<string>();
            foreach (var row in rows)
            {
                fieldName.Add(row.Cells["Column1"].Value?.ToString());
            }
            mode.ClassProperties = mode.ClassProperties.Where(c => fieldName.Contains(c.PropertyName)).ToList();
        }

        private void GenerateEntity(TreeNode selTreeNode)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                if (this.cmb_sol.SelectedValue == null || string.IsNullOrWhiteSpace(this.cmb_sol.SelectedValue.ToString()))
                {
                    MessageBox.Show("请先选择方案！");
                    return;
                }
                if (selTreeNode == null)
                {
                    MessageBox.Show("请选择要生成的类！");
                    return;
                }
                var mode = _ClassModels.Where(c => c.FullName == selTreeNode.Name).FirstOrDefault();
                if (mode == null)
                {
                    MessageBox.Show("生成失败，没有找到类！");
                    return;
                }
                var templateMdoels = SQLCommand.GetSolutionList(Convert.ToInt32(this.cmb_sol.SelectedValue));
                if (templateMdoels == null)
                {
                    MessageBox.Show("生成失败，模板配置获取失败！");
                    return;
                }
                templateMdoels = templateMdoels.OrderBy(c => c.Order).ToList();
                var parentClassModels = new List<ClassModel>();
                SetMsg("正在生成请稍等...");
                foreach (var item in templateMdoels)
                {
                    var m = command.DeepCopy(mode);
                    m.TableModel = GenerateCreateTableSql(mode);
                    m.TemplateMdoel = item;
                    GetGenerateField(m);
                    ClassModelFormat(m, item);


                    // 忽略字段
                    var ignoreFildArr = item.IgnoreField?.Split(';');
                    if (ignoreFildArr?.Length > 0)
                    {
                        m.ClassProperties = m.ClassProperties.Where(c => !ignoreFildArr.Contains(c.PropertyName)).ToList();
                        var keyArr = item.Key.Split(';');
                        m.ClassProperties = m.ClassProperties.Where(c => !keyArr.Contains(c.PropertyName)).ToList();
                    }

                    var entityGeneratePath = item.EntityGeneratePath;
                    ProjectItems projectItems = GetProjectItemsByPath(ref entityGeneratePath, m);

                    if (!string.IsNullOrWhiteSpace(entityGeneratePath))
                    {
                        m.Namespace = $"{entityGeneratePath.Substring(0, entityGeneratePath.Length).Replace("\\", ".").Replace(_ignoreNamespace, "")}";
                        if(m.Namespace.Substring(m.Namespace.Length - 1).Equals("."))
                        {
                            m.Namespace = m.Namespace.Substring(0, m.Namespace.Length - 1);
                        }
                    }
                        

                    var obj = AddClassModelProperty(parentClassModels, m);
                    var fileSuffix = m.TemplateMdoel.FileSuffix;
                    var basePath = Directory.GetCurrentDirectory();
                    GenerateTemplate(projectItems, Path.Combine(basePath, item.RelativePath, item.Name), $"{m.ClassName}{fileSuffix}", obj ?? m);

                    parentClassModels.Add(m);
                    var tjson = JsonConvert.SerializeObject(obj);
                    //if (obj != null)
                    //{
                    //    var t = ((dynamic)obj).TableName;
                    //    //var tt = ((dynamic)obj).CreateInputDto;
                    //}

                    SetMsg(tjson);
                    SetMsg($"“{item.DisplayName}”生成完...");
                }
                MessageBox.Show("生成成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex.Message}");
            }
        }

        private object AddClassModelProperty(List<ClassModel> parentClassModels, ClassModel m)
        {
            if (parentClassModels.Count > 0)
            {
                var pm = parentClassModels[0];
                var obj = ClassHelper.AddProperty(m, new CustPropertyInfo(typeof(ClassModel), pm.TemplateMdoel.Alias), pm);
                for (int i = 1; i < parentClassModels.Count(); i++)
                {
                    pm = parentClassModels[i];
                    obj = ClassHelper.AddProperty(obj, new CustPropertyInfo(typeof(ClassModel), pm.TemplateMdoel.Alias), pm);
                }
                return obj;
            }
            return null;
        }


        private void SetMsg(string msg)
        {
            this.txt_content.Text = $"{this.txt_content.Text}{Environment.NewLine}{msg}";
            txt_content.Focus();
            txt_content.Select(txt_content.Text.Length, 0);
            txt_content.ScrollToCaret();
        }

        private ProjectItems GetProjectItemsByPath(ref string path, ClassModel model)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var pArr = path.Split('\\');
            if (pArr.Count() <= 0)
                throw new Exception("模板生成路径为空！");
            var projectName = pArr[0];
            Project project = null;
            foreach (var item in _SolutionProjects)
            {
                if (item.Name == projectName)
                {
                    project = item;
                    break;
                }
            }
            if (project != null)
            {
                if (pArr.Count() > 1)
                {
                    ProjectItems projectItems = project.ProjectItems;

                    for (int i = 1; i < pArr.Count(); i++)
                    {
                        try
                        {
                            if (string.IsNullOrWhiteSpace(pArr[i]))
                                continue;
                            GeneratePath(ref projectItems, pArr[i], model, ref path);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception($"请检查【{pArr[i]}】文件夹是否已存在，如果存在请包含到解决方案中");
                        }
                    }
                    return projectItems;
                }
                else
                {
                    return project.ProjectItems;
                }
            }
            else
            {
                throw new Exception("模板生成路径有误！");
            }
        }

        private void GeneratePath(ref ProjectItems projectItems, string folderName, ClassModel model, ref string path)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (projectItems == null)
                return;
            if (projectItems.Count == 0 && !string.IsNullOrWhiteSpace(folderName))
            {
                var titem = projectItems.Item(folderName);
                if (titem == null)
                {
                    var fname = ReplaceFolderName(folderName, model.Name);
                    if (projectItems.Item(fname) == null)
                        projectItems = projectItems.AddFolder(fname).ProjectItems;
                    else
                        projectItems = CreateProjectItems(projectItems.Item(fname));
                    path = path.Replace(folderName, fname);
                    return;
                }
            }
            for (int i = 1; i <= projectItems.Count; i++)
            {
                var item = projectItems.Item(i);
                if (item != null && item.Name == folderName)
                {
                    projectItems = CreateProjectItems(item);
                    return;
                }
                if (item != null && item.Name != folderName)
                {
                    var fname = ReplaceFolderName(folderName, model.Name);
                    if (projectItems.Item(fname) == null)
                        projectItems = projectItems.AddFolder(fname).ProjectItems;
                    else
                        projectItems = CreateProjectItems(projectItems.Item(fname));
                    path = path.Replace(folderName, fname);
                    return;
                }
            }
        }

        private ProjectItems CreateProjectItems(ProjectItem projectItem)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (projectItem.ProjectItems != null && projectItem.ProjectItems.Count >= 0)
                return projectItem.ProjectItems;
            if (projectItem.SubProject != null && projectItem.SubProject.ProjectItems != null && projectItem.SubProject.ProjectItems.Count > 0)
                return projectItem.SubProject.ProjectItems;
            return null;
        }

        private string ReplaceFolderName(string folderName, string name)
        {
            if (folderName.Contains("{ClassName}"))
            {
                var bi = folderName.IndexOf('{');
                var ei = folderName.IndexOf('}') + 1;
                var fname = $"{folderName.Substring(0, bi)}{name}{folderName.Substring(ei)}";
                return fname;
            }
            return folderName;
        }

        private void GenerateTemplate(ProjectItems applicationNewFolder, string path, string fileName, object model)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var template = (Template)JinianNet.JNTemplate.Engine.LoadTemplate(path);
            template.Context.EnableTemplateCache = false;
            template.Set("model", model);
            var content = template.Render();
            var contents = content.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Where(c => !string.IsNullOrWhiteSpace(c)).ToArray();
            command.AddFileToProjectItem(applicationNewFolder, contents, fileName);
        }

        private void ClassModelFormat(ClassModel mode, TemplateMdoel templateMdoel)
        {
            mode.ClassName = RemovePrefix(templateMdoel.IgnoreEntityPrefix, mode.ClassName);
            mode.ClassName = RemoveSuffix(templateMdoel.IgnoreEntitySuffix, mode.ClassName);
            mode.Name = command.DeepCopy(mode.ClassName);
            mode.ClassName = $"{templateMdoel.EntityPrefix}{mode.ClassName}{templateMdoel.EntitySuffix}";
            mode.TableName = RemovePrefix(templateMdoel.IgnoreTableNamePrefix, mode.TableName);
            mode.TableName = RemoveSuffix(templateMdoel.IgnoreTableNameSuffix, mode.TableName);
            mode.TableName = $"{templateMdoel.TableNamePrefix}{mode.TableName}{templateMdoel.TableNameSuffix}";
            if (string.IsNullOrWhiteSpace(templateMdoel.Key))
                mode.TemplateMdoel.Key = "Id";
            mode.TemplateMdoel.KeyType = mode.ClassProperties.Where(c => c.PropertyName == templateMdoel.Key).Select(c => c.PropertyType).FirstOrDefault() ?? "int";
        }

        private void CreateFolder(ProjectItems projectItems, int i, string[] arr, ref ProjectItem projectItem)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (i >= arr.Length)
                return;
            string folderName = arr[i];
            projectItem = projectItems.Item(folderName);
            if (projectItem == null)
            {
                projectItem = projectItems.AddFolder(folderName);
            }
            CreateFolder(projectItem.ProjectItems, ++i, arr, ref projectItem);
        }

        /// <summary>
        /// 删除前缀
        /// </summary>
        /// <param name="prefixStr"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        private string RemovePrefix(string prefixStr, string str)
        {
            if (string.IsNullOrWhiteSpace(prefixStr) || string.IsNullOrWhiteSpace(str))
                return str;
            if (str.Length <= prefixStr.Length)
                return str;
            var strArr = str.ToArray();
            for (int i = 0; i < prefixStr.Length; i++)
            {
                if (strArr[i] == prefixStr[i])
                    strArr[i] = ' ';
            }
            return new string(strArr).Trim();
        }

        /// <summary>
        /// 删除后缀
        /// </summary>
        /// <param name="suffixStr"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        private string RemoveSuffix(string suffixStr, string str)
        {
            if (string.IsNullOrWhiteSpace(suffixStr) || string.IsNullOrWhiteSpace(str))
                return str;
            if (str.Length <= suffixStr.Length)
                return str;
            var strArr = str.ToArray();
            for (int i = str.Length - suffixStr.Length, j = 0; j < suffixStr.Length; i++, j++)
            {
                var t1 = strArr[i];
                var t2 = suffixStr[j];
                if (t1 == t2)
                    strArr[i] = ' ';
            }
            return new string(strArr).Trim();
        }

        private void FindCheckNode(TreeNode node, List<TreeNode> listNodes)
        {
            if (node.Checked)
            {
                listNodes.Add(node);
            }
            foreach (TreeNode childnode in node.Nodes)
            {
                FindCheckNode(childnode, listNodes);
            }
        }

        private void treeView1_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                TreeView tree = sender as TreeView;
                if (tree == null)
                    return;
                TreeNode node = tree.GetNodeAt(e.X, e.Y);
                if (node == null)
                    return;
                //SetTreeNodeCheckBoxState(node, node.Checked);
                LoadGird(node.Name);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex}");
            }
        }

        private void btn_tab1_generate_Click(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            GenerateEntity(treeView1.SelectedNode);
        }

        private void btn_del_template_Click(object sender, EventArgs e)
        {
            var rows = GetSelectGridRow(this.dataGridView2);
            var templateIds = new List<long>();
            foreach (var row in rows)
            {
                var template = row.Cells["Column0"].Tag as TemplateMdoel;
                if (template != null)
                    templateIds.Add(template.Id);
            }
            if (templateIds.Count <= 0)
            {
                MessageBox.Show("请先选择要删除的数据！");
                return;
            }
            if (MessageBox.Show("确认删除？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                SQLCommand.RemoveTemplate(templateIds);
                MessageBox.Show("删除成功！");
                LoadTemplateGird();
            }
        }

        private void btn_add_template_Click(object sender, EventArgs e)
        {
            SaveTemplateFrom from = new SaveTemplateFrom();
            from.ShowDialog();
            LoadTemplateGird();
        }

        private void btn_edit_template_Click(object sender, EventArgs e)
        {
            var rows = GetSelectGridRow(this.dataGridView2);
            if (rows.Count <= 0)
            {
                MessageBox.Show("请先选择要编辑的数据！");
                return;
            }
            var en = rows[0].Cells["Column0"].Tag as TemplateMdoel;
            SaveTemplateFrom saveTemplateFrom = new SaveTemplateFrom(en);
            saveTemplateFrom.ShowDialog();
        }

        private void btn_info_template_Click(object sender, EventArgs e)
        {
            var rows = GetSelectGridRow(this.dataGridView2);
            if (rows.Count <= 0)
            {
                MessageBox.Show("请先选择要查看的数据！");
                return;
            }
            var en = rows[0].Cells["Column0"].Tag as TemplateMdoel;

        }

        private void btn_init_Click(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            Init(_dte);
        }

        private void btn_add_prj_Click(object sender, EventArgs e)
        {
            var form = new AddSolutionForm();
            form.Show();
        }

        private void btn_tb2_load_Click(object sender, EventArgs e)
        {
            InitTemplateGridView();
            LoadTemplateGird();
        }

        private void btn_clear_Click(object sender, EventArgs e)
        {
            this.txt_content.Text = "";
        }

        private void btn_set_tmpContent_Click(object sender, EventArgs e)
        {
            var rows = GetSelectGridRow(this.dataGridView2);
            if (rows.Count <= 0)
            {
                MessageBox.Show("请先选择要设置的数据！");
                return;
            }
            var en = rows[0].Cells["Column0"].Tag as TemplateMdoel;
            AddOrEditTemplateForm addOrEditTemplateForm = new AddOrEditTemplateForm(en);
            addOrEditTemplateForm.Show();
        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == -1 || e.RowIndex == -1) return;
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                if (dataGridView2.Rows[i].Cells[0] is DataGridViewCheckBoxCell)
                {
                    DataGridViewCheckBoxCell checkcell = dataGridView2.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                    checkcell.Value = false;
                }
            }
            DataGridViewCheckBoxCell ifcheck = (DataGridViewCheckBoxCell)dataGridView2.Rows[e.RowIndex].Cells[0];
            ifcheck.Value = true;
        }
    }
}
